package com.lagou.homework;

import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.hadoop.mapreduce.TaskAttemptContext;

import java.io.IOException;

public class HomeworkWriter extends RecordWriter<Bean, NullWritable> {

    private FSDataOutputStream out;

    public HomeworkWriter(FSDataOutputStream out) {
        this.out = out;
    }

    private int num = 1;

    @Override
    public void write(Bean bean, NullWritable nullWritable)
            throws IOException, InterruptedException {

        String key = bean.toString();

        // 每一行第一个数是排名，第二个数是数据
        out.write((num+"").getBytes());
        out.write("\t".getBytes());
        out.write(key.getBytes());
        out.write("\r\n".getBytes());

        num++;

    }

    @Override
    public void close(TaskAttemptContext taskAttemptContext)
            throws IOException, InterruptedException {

        IOUtils.closeStream(out);
    }
}
